﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LastFMAlbumArtHelper.cs" company="VCD">
//   (C) 2010
// </copyright>
// <summary>
//   Defines the LastFMAlbumArtHelper type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Id3stuff
{
    using System;
    using System.Data;
    using System.IO;
    using System.Linq;
    using System.Text;

    using id3stuff;

    internal class LastFmAlbumArtHelper : IAlbumartHelper
    {
        private string apiKey;

        public LastFmAlbumArtHelper(string apiKey)
        {
            this.apiKey = apiKey;
        }

        public System.Drawing.Image GetAlbumArtImage(Track track)
        {
            var artist = track.AlbumArtist;
            if (string.IsNullOrEmpty(artist)) artist = track.Artist;

            string url =
                string.Format("http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key={0}&artist={1}&album={2}", this.apiKey, artist, track.Album);
            var httpHelper = new HttpHelper();


            try
            {
                var trackInfo = httpHelper.DownloadWebPage(url);
                var byteArray = Encoding.ASCII.GetBytes(trackInfo);
                var stream = new MemoryStream(byteArray);
                var dt = new DataSet();
                dt.ReadXml(stream);
                string imageUrl = string.Empty;

                foreach (DataRow row in
                    dt.Tables["image"].Rows.Cast<DataRow>().Where(row => row["size"].ToString() == "extralarge" && row["album_Id"].ToString() == "0"))
                {
                    imageUrl = row["image_Text"].ToString();
                }

                return httpHelper.DownloadImage(imageUrl);
            }
            catch (Exception exception)
            {
                System.Diagnostics.Debug.Print(exception.Message);
                return null;
            }
        }
    }
}
